List exercises


In [5]:
# Provided simple test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
    if got == expected:
        prefix = ' OK '
    else:
        prefix = '  X '
    print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))

Fill in the code for the functions below. main() is already set up to call the functions with a few different inputs, printing 'OK' when each function is correct. The starter code for each function includes a 'return' which is just a placeholder for your code.

A. match_ends

Given a list of strings, return the count of the number of strings where the string length is 2 or more and the first and last chars of the string are the same. Note: python does not have a ++ operator, but += works.


In [6]:
def match_ends(words):
  # +++your code here+++
  return

In [7]:
test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)


  X  got: None expected: 3
  X  got: None expected: 2
  X  got: None expected: 1

B. remove_adjacent

Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list.


In [ ]:
def remove_adjacent(nums):
  # +++your code here+++
  return

In [ ]:
test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3])
test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3])
test(remove_adjacent([]), [])

In [ ]:

Note: This notebook is an adaption of Google's python tutorial https://developers.google.com/edu/python


In [ ]: